package org.example.demowebsrocket.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class WebSocketSessionManager {
    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    public void addSession(String username, WebSocketSession session) {
        sessions.put(username, session);
    }

    public void removeSession(String username) {
        WebSocketSession session = sessions.remove(username);
        if (session != null && session.isOpen()) {
            try {
                session.close();
            } catch (IOException e) {
                log.error(Arrays.toString(e.getStackTrace()));
            }
        }
    }

    //getSession
    public WebSocketSession getSession(String username) {
        return sessions.get(username);
    }

    public Set<String> getOnlineUsers() {
        return sessions.keySet();
    }

    public boolean isUserOnline(String username) {
        return sessions.containsKey(username);
    }
}
